#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time


############初识装饰器###################
#计算函数运行时间
def foo():
    print("foo.....")
    time.sleep(2)

def bar():
    print("bar.....")
    time.sleep(3)

def show_time(f):
    def inner():#闭包
        start = time.time()
        f()
        end = time.time()
        print("spend %s" % (end-start))
    return inner

foo = show_time(foo)
# foo()

bar = show_time(bar)
# bar()


###########装饰器改装####################

def show_time(f):
    def inner():#闭包
        start = time.time()
        f()
        end = time.time()
        print("spend %s" % (end-start))
    return inner

@show_time #等价于 foo = show_time(foo)
def foo():
    print("foo.....")
    time.sleep(2)

@show_time #等价于bar = show_time(bar)
def bar():
    print("bar.....")
    time.sleep(3)


# foo()
# bar()




###########装饰器改装参数####################

def show_time(f):
    def inner(*x,**y):#闭包
        start = time.time()
        f(*x,**y)
        end = time.time()
        print("spend %s" % (end-start))
    return inner

@show_time #等价于 foo = show_time(foo)
def foo():
    print("foo.....")
    time.sleep(2)

@show_time #等价于bar = show_time(bar)
def bar(*x,**y):
    sum = 0
    for i in x:
        sum+=i
    print(sum)
    time.sleep(3)


# bar(5,5,1)


###########给装饰器加参数####################
#把装饰器当做闭包
def write_log(log=""):
    def show_time(f):
        def inner(*x,**y):#闭包
            start = time.time()
            f(*x,**y)
            end = time.time()
            print("spend %s" % (end-start))
            if(log == 'true'):
                print("记录日志")
        return inner
    return show_time

@write_log('true') #等价于bar = show_time(bar)
def bar(*x,**y):
    sum = 0
    for i in x:
        sum+=i
    print(sum)
    time.sleep(3)
bar(1,2,3,4,5)

